package com.jack.netty.coder.tlv;

import com.jack.netty.log.LoggerManager;
import com.jack.netty.message.Ping;
import com.jack.netty.message.Pong;
import com.jack.netty.message.UserMsg;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by jack on 2015/5/21 0021.
 */
public class TLVDecoder extends ByteToMessageDecoder{

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

       if(in.readableBytes() < TLVConstants.Tlength){

            return;

       }else{

           in.markReaderIndex();
           int type = in.readInt();
           if(type != Ping.getInstance().getType()
                   && type != Pong.getInstance().getType()
                   && type != UserMsg.type){

               LoggerManager.getInstance().getiLogger().error(getClass(),"type error:" + type + ",id:" + ctx.channel().id().asLongText());
               //in.resetReaderIndex();
               return;
           }else{

               if(type == Ping.getInstance().getType()){

                   out.add(Ping.getInstance());

               }else if(type == Pong.getInstance().getType()){

                   out.add(Pong.getInstance());

               }else if(type == UserMsg.type){

                   if(in.readableBytes() < TLVConstants.Llength){
                       in.resetReaderIndex();
                       return;
                   }else{
                       int length = in.readInt();
                       if(length <= 0){
                           LoggerManager.getInstance().getiLogger().error(getClass(),"消息体不能为空");
                           return;
                       }

                       if(in.readableBytes() < length){
                           in.resetReaderIndex();
                           return;
                       }else{
                           byte[] msg = new byte[length];
                           in.readBytes(msg,0,msg.length);

                           UserMsg userMsg = new UserMsg();
                           userMsg.setLength(length);
                           userMsg.setData(msg);
                           out.add(userMsg);
                       }
                   }
               }else{
                   LoggerManager.getInstance().getiLogger().error(getClass(),"未定义的消息类型:"+type);
               }
           }
       }
    }
}
